package com.qf.fmall2302.filter;

import cn.hutool.jwt.JWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

@Component("jwt")
@Slf4j
public class JwtFilter extends AccessControlFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        HttpServletRequest req = (HttpServletRequest) request;

//0. 判断，如果是浏览器发送的  OPTION请求， 直接放行
        String method = req.getMethod();
        if (method.equals("OPTIONS")){
            return true;
        }

        //1. 获取 请求头中的token
        String token = req.getHeader("token");

        //2. 校验jwttoken
        if(token == null){
            log.info("没带token，拒绝访问");
            return false;
        }

        boolean validate = JWT.of(token)
                .setKey("qfsyjava2302".getBytes())
                .validate(0);


        return validate;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return false;
    }
}
